<?php
	require('../../inc/config.php');
	$item_menu[0] = 'News';
	$item_menu[1] = 'campaign';

	set_time_limit(0);

	ob_implicit_flush(true);
	
	
    $title = 'Enviado Campaña';
	
	$id       = request('id',0);
	$news_id  = request('news_id',0);	
	
	include('../header.php');

	if (!isset($_SESSION["admin"])) {redirect(ADMIN."login.php");	exit(); }


	$cond	= "select * from newsletter where id='$news_id' and activo='1'";
	$rs 	= $db->SelectLimit($cond);
	$News 	= $rs->FetchRow();

	$cond	= "select * from newsletter_campaign where id='$id'";
	$rs 	= $db->SelectLimit($cond);
	$data 	= $rs->FetchRow();
	$lista  = explode(',',$data['listas']);

	$sql = "select * from suscriptores where activo='1' and listas!='' and email!='' ";
	$rs  = $db->Execute($sql);
	$Suscriptores = $rs->GetRows();
	
	foreach($Suscriptores as $clave=>$valor){
		$lista_suscriptor = explode(',',$valor['listas']);
		$existe = false;
		foreach($lista_suscriptor as $ls){
			if(in_array($ls,$lista)){
				$existe = true;
				break;
			}
		}
		if(!$existe){
			unset($Suscriptores[$clave]);
		}
	}
	

	$pagina = file_get_contents(URL."/newsletter/{$News['urlamigable']}.html");	
	
    // ------------------------------------------------------------------- PHP-Mailer
    $PHPMailer_Ruta     = ROOT.'/modules/PHPMailer_5.2.1/';
    include($PHPMailer_Ruta."class.phpmailer.php"); 
    include($PHPMailer_Ruta."class.smtp.php"); 
		$mail = new PHPMailer(); 
		$mail->IsSMTP(); 
		$mail->SMTPAuth   = $MailingSetting['auth']; 
		$mail->SMTPSecure = $MailingSetting['secure']; 
		$mail->Host       = $MailingSetting['host']; 
		$mail->Port       = $MailingSetting['port']; 
		$mail->Username   = $MailingSetting['username']; 
		$mail->Password   = $MailingSetting['password'];
		$mail->CharSet    = "UTF-8";
		$mail->SMTPDebug  = 0;
		
		$mail->SetFrom($MailingSetting['cuenta_salida'], "{$DatosEmpresa['nombre_empresa']}");
		//$mail->AddReplyTo("name@yourdomain.com","First Last");

		$mail->Subject    = $News['titulo'];
		$mail->AltBody    = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
		$mail->MsgHTML($pagina);

	echo "<table style='width:500px;'>";
	echo "<tr><th colspan='2' style='width:300px;'>Destinatario</th><th>Resultado</th></tr>";
	$i=0;
	foreach($Suscriptores as $s){
		$i++;
		
		$nombre = iif(empty($s['nombre']),$s['email'],$s['nombre']);
		$mail->ClearAddresses(); 
		$mail->AddAddress($s['email'], "$nombre"); 

		if(!$mail->Send()) { $resultado = 'Error'; } else { $resultado = 'ok';}
		echo "<tr><td>$i</td><td>$nombre</td><td>$resultado</td></tr>";
		sleep(1);
	}	

	$sql = "update newsletter_campaign set envios = '{$data['envios']}".date("d/m/Y")."($i) - '";
	$ok  = $db->Execute($sql);
	
?>